package com.example.webdemo.controller;

import cn.hutool.core.util.RandomUtil;
import com.example.webdemo.common.ApiResult;
import com.example.webdemo.common.Common;
import com.example.webdemo.common.ResultCodeEnum;
import com.example.webdemo.model.*;
import com.example.webdemo.service.*;
import com.example.webdemo.utils.MyUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zp
 * @version 1.0
 * @description: 前端程序接口
 * @date 2023/7/22 17:58
 */
@RestController
@RequestMapping("/api")
public class WebController {
    @Resource
    private HomeImageService homeImageService;
    @Resource
    private HomeGridService homeGridService;
    @Resource
    private HomeArticleService homeArticleService;
    @Resource
    private ArticleService articleService;
    @Resource
    private SpecialClassificationService specialClassificationService;
    @Resource
    private PhoneCodeService phoneCodeService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private ImageRecordService imageRecordService;
    @Resource
    private TagsService tagsService;
    @Resource
    private ArticleInfoService articleInfoService;

    /**
     * @return ApiResult
     * @description: 获取首页banner图片
     * @author zp
     * @date: 2023/7/22 18:01
     */
    @GetMapping("/getImages")
    public ApiResult getImages() {
        List<HomeImage> homeImages = homeImageService.selectAll();
        return ApiResult.success(homeImages);
    }

    /**
     * @return ApiResult
     * @description: 获取单元菜单数据
     * @author zp
     * @date: 2023/8/1 20:08
     */
    @GetMapping("/getGrids")
    public ApiResult getGrids() {
        List<HomeGrid> homeGrids = homeGridService.selectAll();
        return ApiResult.success(homeGrids);
    }

    /**
     * @return ApiResult
     * @description: 获取首页文章数据
     * @author zp
     * @date: 2023/8/1 20:08
     */
    @GetMapping("/getHomeArticles")
    public ApiResult getHomeArticles(@RequestParam("pageNumber") Integer pageNumber, @RequestParam("pageSize") Integer pageSize) {
        // 设置分页
        PageHelper.startPage(pageNumber, pageSize);
        List<HomeArticle> homeArticles = homeArticleService.selectAll();
        PageInfo<HomeArticle> pageInfo = new PageInfo<>(homeArticles);
        return ApiResult.success(pageInfo);
    }

    /**
     * @return ApiResult
     * @description: 根据文章类型获取文章数据
     * @author zp
     * @date: 2023/8/1 20:08
     */
    @GetMapping("/getArticlesByType")
    public ApiResult getArticlesByType(@RequestParam("pageNumber") Integer pageNumber, @RequestParam("pageSize") Integer pageSize, @RequestParam("type") String type) {
        // 设置分页
        PageHelper.startPage(pageNumber, pageSize);
        List<Article> articles = articleService.selectByType(type);
        PageInfo<Article> pageInfo = new PageInfo<>(articles);
        return ApiResult.success(pageInfo);
    }

    /**
     * @return ApiResult
     * @description: 发送验证码
     * @author zp
     * @date: 2023/7/22 18:02
     */
    @PostMapping("/sendCode")
    public ApiResult sendCode(@RequestBody PhoneCode phoneCode) {
        if (StringUtils.isEmpty(phoneCode.getPhone())) {
            return ApiResult.fail(ResultCodeEnum.USER_PHONE_NULL);
        }
        String code = RandomUtil.randomNumbers(6);   //数字
        phoneCode.setPhoneCode(code);
        int returnCode = phoneCodeService.insert(phoneCode);
        if (returnCode > 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", code);
            return ApiResult.success(map);
        }
        return ApiResult.fail(ResultCodeEnum.SYSTEM_ERROR);
    }

    /**
     * @param phoneCode
     * @return ApiResult
     * @description: 登入
     * @author zp
     * @date: 2023/7/23 16:23
     */
    @PostMapping("/login")
    public ApiResult login(@RequestBody @Validated PhoneCode phoneCode) {
        PhoneCode getPhoneCode = phoneCodeService.selectByPhone(phoneCode.getPhone());
        if (getPhoneCode == null) {
            return ApiResult.fail(ResultCodeEnum.NOT_SEND_CODE);
        }
        if (getPhoneCode.getPhoneCode().equals(phoneCode.getPhoneCode())) {
            userInfoService.login(getPhoneCode);
            Map<String, Object> map = new HashMap<>();
            map.put("token", getPhoneCode.getPhone());
            return ApiResult.success(map);
        }
        return ApiResult.fail(ResultCodeEnum.USER_PHONE);
    }

    /**
     * @param request
     * @return ApiResult
     * @description: 退出登入
     * @author zp
     * @date: 2023/7/28 18:36
     */
    @PostMapping("/logout")
    public ApiResult logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        userInfoService.updateByPhone(null, token);
        return ApiResult.success();
    }

    /**
     * @return ApiResult
     * @description: 获取文章分类
     * @author zp
     * @date: 2023/7/23 16:24
     */
    @GetMapping("/getSpecialClassification")
    public ApiResult getSpecialClassification() {
        List<SpecialClassification> specialClassifications = specialClassificationService.selectAll();
        return ApiResult.success(specialClassifications);
    }

    /**
     * @return ApiResult
     * @description: 获取用户信息
     * @author zp
     * @date: 2023/7/27 19:11
     */
    @GetMapping("/getUserInfo")
    public ApiResult getUserInfo(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        String token = request.getHeader("Authorization");
        UserInfo userInfo = userInfoService.selectByToken(token);
        if (userInfo == null) {
            return ApiResult.fail(ResultCodeEnum.SYSTEM_ERROR);
        }
        resultMap.put("userInfo", userInfo);
        return ApiResult.success(resultMap);
    }

    /**
     * @return ApiResult
     * @description: 获取tag标签
     * @author zp
     * @date: 2023/7/27 19:11
     */
    @GetMapping("/getTags")
    public ApiResult getTags() {
        List<Tag> tags = tagsService.selectAll();
        return ApiResult.success(tags);
    }

    //维修照片上传
    @RequestMapping("/uploadImage")
    @ResponseBody
    public ApiResult uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        //判断非空
        if (Objects.isNull(file) || file.isEmpty()) {
            return ApiResult.fail(ResultCodeEnum.UPDATE_IMAGE_NULL);
        }
        //检查文件大小
        if (file.getSize() > Common.M3_TO_BYTE) {
            return ApiResult.fail(ResultCodeEnum.UPDATE_IMAGE_SIZE_ERROR);
        }
        //检查是否是图片
        BufferedImage bi = ImageIO.read(file.getInputStream());
        if (bi == null) {
            return ApiResult.fail(ResultCodeEnum.UPDATE_IMAGE_TYPE_ERROR);
        }

        String token = request.getHeader("Authorization");
        UserInfo userInfo = userInfoService.selectByToken(token);
        if (userInfo == null) {
            return ApiResult.fail(ResultCodeEnum.SYSTEM_ERROR);
        }

        String fileUrl = MyUtils.saveFile(file);
        if (StringUtils.isEmpty(fileUrl)) {
            return ApiResult.fail(ResultCodeEnum.UPDATE_IMAGE_FAIL);
        }
        Map<String, Object> map = new HashMap<>();
        ImageRecord imageRecord = new ImageRecord();
        imageRecord.setUserId(userInfo.getId());
        imageRecord.setImageUrl(MyUtils.getImageNameByPath(fileUrl));
        imageRecordService.insertSelective(imageRecord);
        map.put("fileUrl", fileUrl);
        return ApiResult.success(map);
    }

    @GetMapping("/deleteImage")
    @ResponseBody
    public ApiResult deleteImage(@RequestParam("fileUrl") String fileUrl, HttpServletRequest request) {
        //判断非空
        if (Objects.isNull(fileUrl) || fileUrl.isEmpty()) {
            return ApiResult.fail(ResultCodeEnum.DELETE_IMAGE_NULL);
        }
        String token = request.getHeader("Authorization");
        UserInfo userInfo = userInfoService.selectByToken(token);
        // 只能删除自己的图片 不能删除其他用户的图片
        ImageRecord imageRecord = imageRecordService.selectByImageUrlAndUser(MyUtils.getImageNameByPath(fileUrl), userInfo.getId());
        if (imageRecord == null) {
            return ApiResult.fail(ResultCodeEnum.DELETE_IMAGE_FILE_NULL);
        }
        // 删除记录 删除文件
        imageRecordService.deleteByPrimaryKey(imageRecord.getId());
        MyUtils.deleteFile(fileUrl);
        return ApiResult.success();
    }

    /**
     * @param request
     * @return ApiResult
     * @description: 保存文章
     * @author zp
     * @date: 2023/7/28 18:36
     */
    @PostMapping("/saveArticle")
    public ApiResult saveArticle(HttpServletRequest request, @RequestBody ArticleInfo articleInfo) {
        String token = request.getHeader("Authorization");
        UserInfo userInfo = userInfoService.selectByToken(token);
        if (userInfo == null) {
            return ApiResult.fail(ResultCodeEnum.SYSTEM_ERROR);
        }
        articleInfo.setUserId(userInfo.getId());
        articleInfo.setAuthor(userInfo.getUserName());

        if (articleInfoService.saveArticleInfoAndArticleTitle(articleInfo) && imageRecordService.deleteImageByType(articleInfo)) {
            return ApiResult.success();
        }
        return ApiResult.fail(ResultCodeEnum.ERROR_SAVE_ARTICLE_INFO);
    }


}
